package com.shenjinzheng.sso.service.impl.member;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenjinzheng.sso.bo.OpenIdBO;
import com.shenjinzheng.sso.config.WeChatConfig;
import com.shenjinzheng.sso.dto.MemberLoginDTO;
import com.shenjinzheng.sso.entity.Member;
import com.shenjinzheng.sso.mapper.MemberMapper;
import com.shenjinzheng.sso.service.MemberAuthService;
import com.shenjinzheng.sso.service.MemberService;
import com.shenjinzheng.sso.utils.JwtUtil;
import com.shenjinzheng.sso.wechat.WeChatAPI;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

@Slf4j
@Service
public class MemberServiceImplByWeChat extends ServiceImpl<MemberMapper, Member> implements MemberAuthService {

    @Resource
    private WeChatConfig weChatConfig;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private MemberService memberService;

    @Override
    public String login(MemberLoginDTO memberLoginDTO) {
        log.info("微信登录逻辑...");
        //1.用code去找微信调用小程序登陆的接口
        //1.1 将请求路径封装到WeChatAPI以便调用
        String url = WeChatAPI.jscode2session;
        //1.2 替换请求路径中的参数
        url = url.replace("{APPID}", weChatConfig.getAppid());
        url = url.replace("{SECRET}", weChatConfig.getSecret());
        url = url.replace("{CODE}", memberLoginDTO.getCode());
        //1.2 请求该路径登录,获取session_key和openid
        String respStr = restTemplate.getForObject(url, String.class);
        //log.info("respStr:{}",respStr);
        OpenIdBO openIdBO = JSON.parseObject(respStr, OpenIdBO.class);
        log.info("{}", openIdBO);
        //2.根据openId 去数据库表member 拿用户信息
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getOpenId, openIdBO.getOpenid());
        Member member = memberService.getOne(wrapper);

        //登录即注册
        if (member == null) {
            //如果member为空->未注册
            member = new Member();//预防空指针
            member.setOpenId(openIdBO.getOpenid());
            this.save(member);
        }
        //签发token
        HashMap<String,Object> map=new HashMap<>();
        map.put("id",member.getId());
        return jwtUtil.createToken(map);

    }

    @Override
    public String getCode(String phone) {
        throw new RuntimeException("微信登陆不需要验证码");
    }
}
